﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ReservaCancha.Models;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;
using System.Text;

namespace ReservaCancha.Controllers
{
    public class RecursoController : Controller
    {

        private List<Recurso> CrearRecursos()
        {
            /*Tipo tipo1 = new Tipo() { Codigo = 1, Nombre = "Árbitro" };
            Tipo tipo2 = new Tipo() { Codigo = 2, Nombre = "Jugador" };
            Tipo tipo3 = new Tipo() { Codigo = 3, Nombre = "Portero" };
            Tipo tipo4 = new Tipo() { Codigo = 4, Nombre = "Equipo deportivo" };
            Recurso recurso1 = new Recurso() { Codigo = 1, Nombre = "VICTOR HUGO CARRILLO CASANOVA", Precio = 50, Tipo = tipo1 };
            Recurso recurso2 = new Recurso() { Codigo = 2, Nombre = "MIGUEL ANGEL SANTIVAÑEZ DE LA CRUZ", Precio = 50, Tipo = tipo1 };
            Recurso recurso3 = new Recurso() { Codigo = 3, Nombre = "HENRY PERCY GAMBETTA AVALOS", Precio = 50, Tipo = tipo1 };
            Recurso recurso4 = new Recurso() { Codigo = 4, Nombre = "DIEGO MIRKO HARO SUELDO", Precio = 30, Tipo = tipo2 };
            Recurso recurso5 = new Recurso() { Codigo = 5, Nombre = "HECTOR ESTUARDO ROJAS FIGUEROA", Precio = 30, Tipo = tipo2 };
            Recurso recurso6 = new Recurso() { Codigo = 6, Nombre = "RAUL EDUARDO LOPEZ CRUZ", Precio = 30, Tipo = tipo3 };
            Recurso recurso7 = new Recurso() { Codigo = 7, Nombre = "22 CAMISETAS", Precio = 10, Tipo = tipo4 };
            List<Recurso> recursos = new List<Recurso>();
            recursos.Add(recurso1);
            recursos.Add(recurso2);
            recursos.Add(recurso3);
            recursos.Add(recurso4);
            recursos.Add(recurso5);
            recursos.Add(recurso6);
            recursos.Add(recurso7);*/
            HttpWebRequest req = (HttpWebRequest)WebRequest
                .Create("http://localhost:5158/Recursos.svc/Recursos");
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            string recursoJson = reader.ReadToEnd();
            JavaScriptSerializer js = new JavaScriptSerializer();
            List<Recurso> recursos = js.Deserialize<List<Recurso>>(recursoJson);
            return recursos;
        }

        private Recurso ObtenerRecurso(int codigo)
        {
            /*List<Recurso> recursos = (List<Recurso>) Session["recursos"];
            Recurso model = recursos.Single(delegate(Recurso recurso)
            {
                if (recurso.Codigo == codigo)
                    return true;
                else
                    return false;
            });*/
            string codigo1 = Convert.ToString(codigo);
            HttpWebRequest req = (HttpWebRequest)WebRequest
                .Create("http://localhost:5158/Recursos.svc/Recursos/"+codigo1);
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            string recursoJson = reader.ReadToEnd();
            JavaScriptSerializer js = new JavaScriptSerializer();
            List<Recurso> recursos = js.Deserialize<List<Recurso>>(recursoJson);
            Recurso model = js.Deserialize<Recurso>(recursoJson);
            return model;
        }
        //
        // GET: /Recurso/

        public ActionResult Index()
        {
            if (Session["recursos"] == null)
                Session["recursos"] = CrearRecursos();

            HttpWebRequest req = (HttpWebRequest)WebRequest
                .Create("http://localhost:5158/Recursos.svc/Recursos");
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            string recursoJson = reader.ReadToEnd();
            JavaScriptSerializer js = new JavaScriptSerializer();
            List<Recurso> model = js.Deserialize<List<Recurso>>(recursoJson);
            //List<Recurso> model = (List<Recurso>)Session["recursos"];
            return View(model);
        }

        //
        // GET: /Recurso/Details/5

        public ActionResult Details(int id)
        {
            Recurso model = ObtenerRecurso(id);
            return View(model);
        }

        //
        // GET: /Recurso/Create

        public ActionResult Create()
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest
                .Create("http://localhost:5158/Tipos.svc/Tipos");
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            string tipoJson = reader.ReadToEnd();
            JavaScriptSerializer js = new JavaScriptSerializer();
            List<Tipo> tipos = js.Deserialize<List<Tipo>>(tipoJson);
            var list = new SelectList(tipos, "Codigo", "Nombre");
            ViewData["tipos"] = list;
            return View();
        } 

        //
        // POST: /Recurso/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                if (collection["codigo"] == null || collection["codigo"].Trim().Equals("") || collection["nombre"] == null || collection["precio"]==null)
                {
                 TempData["mensaje"] = "Ingrese todos los datos por favor";
                 HttpWebRequest req1 = (HttpWebRequest)WebRequest
               .Create("http://localhost:5158/Tipos.svc/Tipos");
                 req1.Method = "GET";
                 HttpWebResponse res1 = (HttpWebResponse)req1.GetResponse();
                 StreamReader reader1 = new StreamReader(res1.GetResponseStream());
                 string tipoJson = reader1.ReadToEnd();
                 JavaScriptSerializer js1 = new JavaScriptSerializer();
                 List<Tipo> tipos = js1.Deserialize<List<Tipo>>(tipoJson);
                 var list = new SelectList(tipos, "Codigo", "Nombre");
                 ViewData["tipos"] = list;
                  return View("Create");
                }
                string postdata = "{\"Codigo\":\"" + collection["Codigo"] + "\",\"Nombre\":\"" + collection["nombre"] + "\" ,\"Precio\":\"" + collection["precio"] + "\",\"Tipo\":\"" + collection["tipos"] + "\" }";
                byte[] data = Encoding.UTF8.GetBytes(postdata);
                HttpWebRequest req = (HttpWebRequest)WebRequest
                    .Create("http://localhost:5158/Recursos.svc/Recursos");
                req.Method = "POST";
                req.ContentLength = data.Length;
                req.ContentType = "application/json";
                var reqStream = req.GetRequestStream();
                reqStream.Write(data, 0, data.Length);
                HttpWebResponse res = null;
                res = (HttpWebResponse)req.GetResponse();
                StreamReader reader = new StreamReader(res.GetResponseStream());
                string recursoJson = reader.ReadToEnd();
                JavaScriptSerializer js = new JavaScriptSerializer();
                Recurso recursoCreado = js.Deserialize<Recurso>(recursoJson);
                return RedirectToAction("Index");
            }catch (WebException e)
                {
                    HttpWebResponse resError = (HttpWebResponse)e.Response;
                    StreamReader reader2 = new StreamReader(resError.GetResponseStream());
                    string error = reader2.ReadToEnd();
                    JavaScriptSerializer js = new JavaScriptSerializer();
                    string errorMessage = js.Deserialize<string>(error);
                    TempData["mensaje"] = errorMessage;
                    HttpWebRequest req = (HttpWebRequest)WebRequest
                .Create("http://localhost:5158/Tipos.svc/Tipos");
                    req.Method = "GET";
                    HttpWebResponse res = (HttpWebResponse)req.GetResponse();
                    StreamReader reader = new StreamReader(res.GetResponseStream());
                    string tipoJson = reader.ReadToEnd();
                    JavaScriptSerializer js1 = new JavaScriptSerializer();
                    List<Tipo> tipos = js1.Deserialize<List<Tipo>>(tipoJson);
                    var list = new SelectList(tipos, "Codigo", "Nombre");
                    ViewData["tipos"] = list;
                    return View("Create");

                }

        }
        
        //
        // GET: /Recurso/Edit/5
 
        public ActionResult Edit(int id)
        {
            Recurso model = ObtenerRecurso(id);
            HttpWebRequest req = (HttpWebRequest)WebRequest
                .Create("http://localhost:5158/Tipos.svc/Tipos");
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            string tipoJson = reader.ReadToEnd();
            JavaScriptSerializer js = new JavaScriptSerializer();
            List<Tipo> tipos = js.Deserialize<List<Tipo>>(tipoJson);
            var list = new SelectList(tipos, "Codigo", "Nombre");
            ViewData["tipos"] = list;
            return View(model);
        }

        //
        // POST: /Recurso/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                Recurso model = ObtenerRecurso(id);
               //string precio1 = Convert.ToString(precio);
                //string postdata1 = "{\"Codigo\":\"1\",\"Nombre\":\"eduuu\",\"Precio\":\"300\"}";
                string postdata1 = "{\"Codigo\":\"" + collection["Codigo"] + "\",\"Nombre\":\"" + collection["nombre"] + "\" ,\"Precio\":\"" + collection["precio"] + "\",\"Tipo\":\"" + collection["tipos"] + "\" }";
                byte[] data1 = Encoding.UTF8.GetBytes(postdata1);
                HttpWebRequest req3 = (HttpWebRequest)WebRequest
                    .Create("http://localhost:5158/Recursos.svc/Recursos");
                req3.Method = "PUT";
                req3.ContentLength = data1.Length;
                req3.ContentType = "application/json";
                var reqStream1 = req3.GetRequestStream();
                reqStream1.Write(data1, 0, data1.Length);
                var res3 = (HttpWebResponse)req3.GetResponse();
                StreamReader reader3 = new StreamReader(res3.GetResponseStream());
                string recursoJson3 = reader3.ReadToEnd();
                JavaScriptSerializer js3 = new JavaScriptSerializer();
                Recurso recursoModificado = js3.Deserialize<Recurso>(recursoJson3);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Recurso/Delete/5
 
        public ActionResult Delete(int id)
        {
            Recurso model = ObtenerRecurso(id);
            return View(model);
        }

        //
        // POST: /Recurso/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                /*List<Recurso> recursos = (List<Recurso>) Session["recursos"];
                recursos.Remove(ObtenerRecurso(id));*/
                string postdata2 = "{\"Codigo\":\"" + collection["Codigo"] + "\"}";
                byte[] data2 = Encoding.UTF8.GetBytes(postdata2);
                HttpWebRequest req4 = (HttpWebRequest)WebRequest
                    .Create("http://localhost:5158/Recursos.svc/Recursos/"+id);
                req4.Method = "DELETE";
                req4.ContentLength = data2.Length;
                req4.ContentType = "application/json";
                var reqStream2 = req4.GetRequestStream();
                reqStream2.Write(data2, 0, data2.Length);
                var res4 = (HttpWebResponse)req4.GetResponse();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
